package com.yanqu.road.dao.db;

import com.yanqu.road.utils.TimeHelper;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;


public class DbMonitor {
	public static final Logger log = LogManager.getLogger(DbMonitor.class.getName());

	public static final Logger sqlLog = LogManager.getLogger("druid.sql");

	private static AtomicInteger connOpenNum = new AtomicInteger();
	private static AtomicInteger connCloseNum = new AtomicInteger();

	private List<String> steps = new LinkedList<String>();

	private long first = 0;

	private String sql;

	public DbMonitor() {
		first = TimeHelper.getSysCurTimeMillis();
		steps.add("start");
	}

	public void execComplete(String sql) {
		this.sql = sql;
		steps.add("exec");

	}

	public void openConnection() {
		steps.add("open");
		connOpenNum.incrementAndGet();
	}

	public void closeConnection() {
		steps.add("close");

		int closeSize = connCloseNum.incrementAndGet();
		int openSize = connOpenNum.get();
		if (Math.abs(closeSize - openSize) > 20) {
			// log.debug("all connections [{}], close connection [{}], sql {}", openSize, closeSize, sql);
		}

		long second = TimeHelper.getSysCurTimeMillis();
		double spendTime = (second - first);
		if (DBPoolManager.getPropertiesFile().getProperty("DBWatch").equals("1")) {

			sqlLog.debug("sql spend time {} Millis, {}, {}", spendTime, steps, sql);

		}
		if (spendTime > 999) {
			log.warn(" sql spend time {} Millis, {}, {}", spendTime, steps, sql);
		}
	}
}
